const $sql = require('../sql/sqlMap')
const moment = require('moment')
const $http = require('../sql/http')
const $time = require('../utils/time')
const jwt = require('jwt-simple')
const express = require('express')
const fs = require('fs')

const {rootPath} = require('../rootPath')
const app = express()
app.set('jwtTokenSecret', 'YOUR_SECRET_STRING')
function formatData(rows) {
    return rows.map(row => {
      if(row.create_time) {
        row.create_time = $time.formatTime(row.create_time)
      }
      if(row.update_time) {
        row.update_time = $time.formatTime(row.update_time)
      }
      let type = row.type
      if(type){
        switch(type) {
          case 1:
            row.role = '管理员'
            break
          case 2:
            row.role = '普通用户'
            break
        }
      }
      return Object.assign({}, row)
    })
  }
function getFileInfo(file){
    // 处理文件类型
    const fileTypeArr=file.mimetype.split('/')
    const type = fileTypeArr[0]
    const map ={
      'image':'图片',
      'audio':'音频',
      'video':'视频',
      'application':{
        'document':'word文档',
      }
    }
    let fileType = map[type];
    let fileMime = fileTypeArr[1]
      if(type=='application'){
      // this.fileType = '音频'
       if(fileMime.length>3){
         const mime =fileMime.split('.')
         const {length} = mime;
         fileType = map[type][mime[length-1]]
         fileMime = map[type][mime[length-1]]
       }else{
          fileType ='pdf文档'
       }
      
    }
    //梳理文件大小
    let size = Math.floor(file.size/Math.pow(1024,2) * 100) /100
    let fileSize = size;
    return {
        fileType,
        fileMime,
        fileSize
    }
  }
const file = {
    /*添加文件 start */
    add(req,res){
        const baseUrl = req['headers']['x-forwarded-proto'] + '://' +req['headers']['host']
        // return
        const params = req.body;
        const insertData=[]
        req.files.forEach((file,i)=>{
           const { 
            fileType,
            fileMime,
            fileSize} =getFileInfo(file);
            const index =file.filename.lastIndexOf('.')
            const fileName = file.filename.slice(0,index)
            const obj = {
                id:new Date().getTime()+i,
                fileType,
                fileMime,
                fileSize,
                fileName,
                fileLocation:baseUrl+'/'+rootPath+file.filename,
                createTime:Date.now(),
                createMan:params.createMan,
                fileDesc:params.fileDesc ? params.fileDesc :'暂无描述'
            };
            insertData.push(obj);
           
        })
        $http.userVerify(req, res, () => {
            if(!req.files.length) $http.writeJson(res, {code: 2, message:'传入文件不能为空'})
            else {
              let sql = $sql.file.add
            const values = insertData.map(item=>{
                return [
                    item.id,
                    item.fileName,
                    item.fileDesc,
                    item.fileMime,
                    item.fileType,
                    item.fileLocation,
                    item.fileSize,
                    item.createTime,
                    item.createMan
                ]
            })
              $http.connPool(sql,[values] ,(err, result) => {
                if(err) return $http.writeJson(res, {code:-2, message:'上传文件失败',errMsg: err})
                if(result.affectedRows == 0) return $http.writeJson(res, {code: 2, message:'上传失败'})
                return $http.writeJson(res, {code: 1, message: '上传成功'})
              })
            }
          })
    },
    /*添加文件 end */
    /*修改文件 start */
    update(req,res){
        const params = req.body;
        const baseUrl = req['headers']['x-forwarded-proto'] + '://' +req['headers']['host']
        $http.userVerify(req, res, (info) => {
            let fileName = params.fileName;
            let fileDesc = params.fileDesc;
            let fileId = params.fileId;
            let fileLocation = params.fileLocation;
            const filePath = fileLocation.split('/')
            const Path = `${rootPath}`+filePath[filePath.length-1]
            if(fs.existsSync(Path)){
                const index =fileLocation.lastIndexOf('.');
                const ext = fileLocation.slice(index)
                 fs.renameSync(Path,rootPath+fileName+ext);
                //  改路径地址
                fileLocation = baseUrl+'/'+rootPath+fileName+ext
            }
            if(!fileName) {$http.writeJson(res, {code: 2, message:'参数有误'})}
            else {
              let sql = $sql.file.update
              let arrayParams = [fileDesc,fileName,fileLocation,fileId]
              $http.connPool(sql, arrayParams, (err, result) => {
                if(err) return $http.writeJson(res, {code:-2, message:'失败',errMsg: err})
                if(result.affectedRows != 1) return $http.writeJson(res, {code: 2, message:'更新失败'})
             
                return $http.writeJson(res, {code: 1, data: result, message: '修改成功'})
              })
            }
          })
    },
    /*修改文件 end */
    /*删除文件 start */
    del(req,res){
        const params = req.body;
        $http.userVerify(req, res, (info) => {
            let id = info.iss
            if(!id) {
              $http.writeJson(res, {code: 2, message:'token失效'})
            } else {
                params.forEach(e=>{
                   const filePath = e.fileLocation.split('/')
                   const Path = rootPath+filePath[filePath.length-1]
                   if(fs.existsSync(Path)){
                        fs.unlinkSync(Path,(err)=>{
                            if(err) throw err
                        })
                   }
                })
              let sql = $sql.file.del
              sql+=`(${params.map(e=>e.fileId).join(',')})`
              let arrayParams = []
              $http.connPool(sql, arrayParams, (err, result) => {
                if(err) return $http.writeJson(res, {code:-2, message:'删除失败',errMsg: err})
                if(result.affectedRows == 0) return $http.writeJson(res, {code: 2, message:'删除失败'})
                return $http.writeJson(res, {code: 1, message: '删除用户成功'})
             
              })
            }
          })
    },
    /*删除文件 end */
    /*查询文件 start */
    list(req,res){
        const params = req.body;
        // { fileName:1 , startTime:}
        //如果startTime不为空的话就  拼上  and createTime >= startTime and  createTime <= endTime LIMT 0,15
        //反之  拼上  LIMT 0,15
        $http.userVerify(req, res, () => {
            let sqlSelectTotal = $sql.file.fileTotal
            let sqlSelectList= $sql.file.list
            const fileName = params.fileName;
            const startTime = params.startTime;
            const endTime = params.endTime
      
            params.pageSize = !params.pageSize ? 10 : params.pageSize
            // 分页查询入参 start
            let limitFirst = (params.pageNum-1)*params.pageSize;
            let limitLast = params.pageSize;
            // 分页查询入参 end
            if(fileName){
                // sqlSelectList+=' fileName like '+'%'+'+fileName+'%';
                sqlSelectList+=`where fileName like '%${fileName}%'`;
            }
            if(startTime && fileName){
                sqlSelectList+=' and (createTime >= ' + startTime + ' and createTime <= ' +endTime+')'
            }
            if(startTime && !fileName){
                sqlSelectList+='where createTime >= ' + startTime + ' and createTime <= ' +endTime
            }
           
            let sql= sqlSelectTotal + '; ' + sqlSelectList
            sql +=' order by createTime desc limit ?,? '; // 
            let arrayParams = [limitFirst, limitLast]
            $http.connPool(sql, arrayParams, (err, result) => {
              if(err) {
                return $http.writeJson(res, {code:-2, message:'失败',errMsg: err})
              } else {
                let resultData = {}
                resultData.totalCount = result[0][0]['totalCount']
                resultData.list = formatData(result[1])
                return $http.writeJson(res, {code: 1, data: resultData, message: '获取文件列表成功'})
              }
            })
          })
    },
    /*查询文件 end */
}
module.exports=file